﻿using System;
using UnityEngine;
using UnityEngine.Pool;


namespace UIFramwork.Pool
{
    /// <summary>
    /// UI 池
    /// </summary>
    public class UnitUIPool : MonoBehaviour
    {
        [Tooltip("页面池")] ObjectPool<GameObject> m_PoolCatolog;
        [Tooltip("预制体")] GameObject m_Prefab;
        [Tooltip("本池名")] Type m_PoolType;


        /// <summary>
        /// 设置池
        /// </summary>
        public void Set(Type type)
        {
            this.m_PoolType = type;
        }

        /// <summary>
        /// 设置池原型
        /// </summary>
        public void Set(GameObject prefab)
        {
            this.m_Prefab = prefab;

            if (this.m_PoolCatolog != null && this.m_PoolCatolog.CountAll != 0)
            {
                this.m_PoolCatolog.Dispose();
            }

            this.m_PoolCatolog = new ObjectPool<GameObject>(DoCreate, DoGet, DoRelease, DoDestroy, true, 1, 20);
        }


        public GameObject Get() => this.m_PoolCatolog.Get();
        public void Recycle(GameObject arg) => this.m_PoolCatolog.Release(arg);
        public void Dispose() => this.m_PoolCatolog.Dispose();
        


        #region 池逻辑
        private void DoDestroy(GameObject arg)
        {
            Destroy(arg);

#if UNITY_EDITOR
            this.gameObject.name = $"{m_PoolType.Name} [使用情况]{m_PoolCatolog.CountActive}/{m_PoolCatolog.CountAll}";
#endif
        }
        private void DoRelease(GameObject arg)
        {
            arg.transform.SetParent(this.transform);
            arg.SetActive(false);
#if UNITY_EDITOR
            this.gameObject.name = $"{m_PoolType.Name} [使用情况]{m_PoolCatolog.CountActive}/{m_PoolCatolog.CountAll}";
#endif
        }
        private void DoGet(GameObject arg)
        {
            arg.SetActive(true);

#if UNITY_EDITOR
            this.gameObject.name = $"{m_PoolType.Name} [使用情况]{m_PoolCatolog.CountActive}/{m_PoolCatolog.CountAll}";
#endif
        }
        private GameObject DoCreate()
        {
            GameObject theClone = GameObject.Instantiate(this.m_Prefab, transform);
            {
                theClone.name = $"[克隆] {m_PoolType}";
                theClone.transform.SetParent(transform);
                theClone.GetComponent<Transform>().localScale = Vector3.one;
            }

#if UNITY_EDITOR
            this.gameObject.name = $"{m_PoolType.Name} [使用情况]{m_PoolCatolog.CountActive}/{m_PoolCatolog.CountAll}";
#endif
            return theClone;
        }
        #endregion
    }
}
